<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Have\Controller;
use Think\Controller;
use Think\Exception;
/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class HaveController extends Controller {
    
    protected $Usertype = 0;
    
    public function _empty() {
        $this->redirect('Index/index');
    }

    /**
     * 后台控制器初始化
     */
    protected function _initialize(){
        define('UID', his_login());
        if (!UID) {
            $this->redirect('Public/login');
        }

        define('USER_AUTH', hget_auth());

        $menus = $this->getMenus();
        $curmenu = $this->curMenus(CONTROLLER_NAME, ACTION_NAME);
        foreach ($menus['main'] as $key => $item) {
            if (strtolower($curmenu)== strtolower($item['url'])) {
                $menus['main'][$key]['class'] = 'active';
            } else {
                if (is_array($item['child'])) {
                    foreach ($item['child'] as $val) {
                        if (!is_array($item['url']) && strtolower($curmenu) == strtolower($val['url']))
                        {
                            $menus['main'][$key]['class'] = 'active';
                        }else if (is_array($item['url'])) {
                            foreach ($val['url'] as $url) {
                                if (strtolower($curmenu) == strtolower($url)) {
                                    $menus['main'][$key]['class'] = 'active';
                                }
                            }
                        }
                    }
                }
            }
        }
        switch (USER_AUTH) {
            case 0:
            case 1:
                $role = '超级管理员';
                break;
            case 2:
                $role = '管理员';
                break;
            case 3:
                $role = '用户';
                break;
            default:
                $this->redirect('Public/login');
                break;
        }
        try {
            $map['username'] = session('user_auth.username');
            $m = M('UcenterMember')->where($map)->field('ptype')->find();
            $this->Usertype = $m['ptype'];
        }catch (Exception $er) {
            $this->Usertype = 255;
        }
        $this->assign('__MENU__', $menus);
        $this->assign('role', $role);
        $this->assign('usertype', $this->Usertype);
        $this->assign('script', $this->getMapapi());
    }
    
    final protected function curMenus($controller='', $method='') {
        if (empty($controller) || empty($method)) {
            return '';
        }
        return $controller.'/Index';
    }

    final protected function getCurDev(){
        try {
            $m = null;
            if ($this->Usertype != 0) {
                $map['insurer_id'] = $this->Usertype;
                $m = M('insurer_policy', 'zb_', 'ZHIBAO_CONFIG')->where($map)->field('c_lcn_no')->select();
            } else {
                $m = M('insurer_policy', 'zb_', 'ZHIBAO_CONFIG')->field('c_lcn_no')->select();
            }
            unset($map);
            $map['stoptime'] = array('like', date('Y-m-d').'%');
            $obdid = M('allobd')->where($map)->field('obdid,stoptime')->select();
            unset($map);
            $dev = array();
            foreach ($obdid as $key => $val) {
                $dev[$key] = $val['obdid'];
            }
            $carno = array();
            foreach ($m as $key => $val) {
                $carno[$key] = $val['c_lcn_no'];
            }
            $map['car_no'] = array('in', $carno);
            $map['obdid'] = array('in', $dev);
            $map['ptype'] = 0; 
            $m = M('user_car', 'zb_', 'ZHIBAO_CONFIG')->where($map)->group('obdid')->field('drv_owner,car_no,obdid')->select();
            foreach ($m as $key => $val) {
                foreach ($obdid as $k => $v) {
                    if ($val['obdid'] == $v['obdid']) {
                        $m[$key]['stoptime'] = $v['stoptime'];
                    }
                }
            }
            return $m;
        } catch (\Exception $e) {
            return null;
        }
    }
    
    final protected function getOffDev(){
        try {
            $m = null;
            if ($this->Usertype != 0) {
                $map['insurer_id'] = $this->Usertype;
                $m = M('insurer_policy', 'zb_', 'ZHIBAO_CONFIG')->where($map)->field('c_lcn_no')->select();
            } else {
                $m = M('insurer_policy', 'zb_', 'ZHIBAO_CONFIG')->field('c_lcn_no')->select();
            }
            unset($map);
            $map['stoptime'] = array('notlike', date('Y-m-d').'%');
            $obdid = M('allobd')->where($map)->field('obdid,stoptime,UNIX_TIMESTAMP(stoptime)')->select();
            unset($map);
            $dev = array();
            foreach ($obdid as $key => $val) {
                $dev[$key] = $val['obdid'];
            }
            $carno = array();
            foreach ($m as $key => $val) {
                $carno[$key] = $val['c_lcn_no'];
            }
            $map['car_no'] = array('in', $carno);
            $map['obdid'] = array('in', $dev);
            $map['ptype'] = 0;
            $m = M('user_car', 'zb_', 'ZHIBAO_CONFIG')->where($map)->field('drv_owner,car_no,obdid')->select();
            foreach ($m as $key => $val) {
                foreach ($obdid as $k => $v) {
                    if ($val['obdid'] == $v['obdid']) {
                        $m[$key]['stoptime'] = $v['stoptime'];
                        $m[$key]['unix_timestamp(stoptime)'] = $v['unix_timestamp(stoptime)'];
                    }
                }
            }
            return $m;
        } catch (\Exception $e) {
            return null;
        }
    }

    final protected function getAllDev() {
        try {
            $obd = M('allobd');
            $obdid = $obd->field('obdid,type')->select();
            return $obdid;
        }catch(\Exception $ex) {
            return array();
        }
    }

    final protected function getDate($format='Ymd') {
        return date($format);
    }
    
    final protected function getMapapi() {
        $mapapi = session('MAP_API_SRC');
        if (empty($mapapi)) {
            $ak = C('API_KEY');
            if (empty($ak))
                return null;
                $mapapi = 'http://api.map.baidu.com/api?v=2.0&ak='.$ak;
                session('MAP_API_SRC', $mapapi);
        }
        return $mapapi;
    }
    
    /**
     * 对数据表中的单行或多行记录执行修改 GET参数id为数字或逗号分隔的数字
     *
     * @param string $model 模型名称,供M函数使用的参数
     * @param array  $data  修改的数据
     * @param array  $where 查询时的where()方法的参数
     * @param array  $msg   执行正确和错误的消息 array('success'=>'','error'=>'', 'url'=>'','ajax'=>false)
     *                     url为跳转页面,ajax是否ajax方式(数字则为倒数计时秒数)
     *
     * @author 朱亚杰  <zhuyajie@topthink.net>
     */
    final protected function editRow ( $model ,$data, $where , $msg ){
       // $where = array_merge( array('id' => array('in', $id )) ,(array)$where );
        $msg   = array_merge( array( 'success'=>'操作成功！', 'error'=>'操作失败！', 'url'=>'' ,'ajax'=>IS_AJAX) , (array)$msg );
        $a = M($model)->where($where)->save($data);
        if( $a!==false ) {
            $this->success($msg['success'],$msg['url'],$msg['ajax']);
        }else{
            $this->error($msg['error'],$msg['url'],$msg['ajax']);
        }
    }

    
    /**
     * 获取控制器菜单数组,二级菜单元素位于一级菜单的'_child'元素中
     * @author 朱亚杰  <xcoolcc@gmail.com>
     */
    final public function getMenus($controller=CONTROLLER_NAME){
        $menus = session('HAVE_MENU_LIST');
        if (empty($menus)) {
            $menus['main'] = array(
                array('url' => 'Index/index', 'title' => '首页', 'logo' => 'laptop'),
                array('url' => 'Device/index', 'title' => '设备管理', 'logo'=> 'copy',
                    'child'=>array(
                    array('title' => '设备状态', 'url'=>'Device/index'),
                    array('title' => '所有设备', 'url'=> 'Device/show'),
                   // array('title' => '车辆信息', 'url' => 'Device/carshow'),
                    array('title' => '查看历史记录', 'url'=>'Device/history'),
                    array('title' => '车主OBD管理', 'url' => 'Device/manadev')
        		)
                ),
                array('url' => 'Map/index', 'title' => '地图', 'logo' => 'map-marker', 
                    'child'=>array(
                    array('title' => '车辆运动轨迹',
                        'url' => 'Map/index')
                    ),
                ),
                array('url' => 'User/index', 'title' => '用户', 'logo' => 'table', 'child'=>array(
                    array('title' => '用户信息', 'url'=>'User/index'),
                    'auth' => array('title' => '权限管理', 'url' => 'User/auth_manager'),
                )),
                array('url' => 'Register/index', 'title' => '注册', 'logo' => 'font', 'child'=>array(
                    array('title' => '注册', 'url'=>'Register/index'),
                    array('title' => '登录', 'url'=>'Register/login')
                ))
        
            );
            if (USER_AUTH != 0) {
                unset($menus['main'][3]['child']['auth']);
            }
            if (USER_AUTH > 1) {
                unset($menus['main'][2]);
                unset($menus['main'][1]['child'][2]);
                unset($menus['main'][1]['child'][3]);
            }

            session('HAVE_MENU_LIST', $menus);
        }
        return $menus;
    }

}
